package org.geektimes.configuration.microprofile.config.sources;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.eclipse.microprofile.config.spi.ConfigSource;

public abstract class MappedAbstractConfigSource implements ConfigSource {

	private int ordinal;

	private String name;

	private Map<String, String> properties;

	public MappedAbstractConfigSource(int ordinal, String name) {
		this(ordinal, name, true);
	}

	public MappedAbstractConfigSource(int ordinal, String name, boolean initial) {
		this.ordinal = ordinal;
		this.name = name;
		if (initial)
			this.properties = getProperties();
	}

	public Map<String, String> getProperties() {

		Map<String, String> configProperties = new HashMap<String, String>();
		try {
			prepareProperties(configProperties);
		} catch (Throwable throwable) {
			throw new IllegalStateException("准备配置数据发生错误", throwable);
		}
		return Collections.unmodifiableMap(configProperties);
	}

	@Override
	public Set<String> getPropertyNames() {
		return properties.keySet();
	}

	@Override
	public String getValue(String propertyName) {
		return properties.get(propertyName);
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public int getOrdinal() {
		return ordinal;
	}

	protected abstract void prepareProperties(Map<String, String> properties) throws Throwable;
}
